package com.demo.cookie;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet(urlPatterns = "/cookie")
public class CookieDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("request................");
        resp.setContentType("text/html;chatset=utf-8");

        // 在服务器端创建Cookie对象
        // 如果要给Cookie中存储中文，建议对中文进行编码处理%E7%B1%B3
        String value = URLEncoder.encode("张三","utf-8");
        Cookie cookie = new Cookie("username",value);
        Cookie cookie2 = new Cookie("age","20");

        // 需要将cookie添加到response中
        resp.addCookie(cookie);
        resp.addCookie(cookie2);


        // 基于本次的请求，给客户端响应数据
        PrintWriter out = resp.getWriter();
        out.write("你好");
    }
}
